<template>
  <div>
    <button @click="downloadPdf" class="download-btn">下载PDF</button>

    <el-button type="primary" @click="previewPdfSimple" icon="el-icon-view">预览PDF(简单版)</el-button>


    <!-- PDF预览对话框 -->
    <el-dialog
        title="PDF预览"
        :visible.sync="simpleDialogVisible"
        width="80%"
        top="5vh">
      <iframe
          :src="simplePdfUrl"
          width="100%"
          height="600px"
          style="border: none;"
      ></iframe>
      <span slot="footer" class="dialog-footer">
        <el-button @click="simpleDialogVisible = false">关闭</el-button>
      </span>
    </el-dialog>

  </div>
</template>

<script>


import axios from 'axios';

export default {

  data() {
    return {
      pdfDialogVisible: false,
      pdfUrl: null,
      simpleDialogVisible: false,
      simplePdfUrl: null,
      numPages: 1
    }
  },
  methods: {
    async previewPdfSimple() {
      try {
        // 直接使用后端预览接口URL
        this.simplePdfUrl = 'http://localhost:8090/api/download/preview-pdf';
        this.simpleDialogVisible = true;
      } catch (error) {
        console.error('预览失败:', error);
        this.$message.error('PDF预览失败');
      }
    },
    async downloadPdf() {
      try {
        const response = await axios({
          method: 'get',
          url: 'http://localhost:8090/api/download/pdf', // 根据你的实际后端地址调整
          responseType: 'blob' // 重要！必须指定响应类型为blob
        });

        // 创建一个临时的URL对象
        const url = window.URL.createObjectURL(new Blob([response.data]));

        // 创建一个临时的a标签用于下载
        const link = document.createElement('a');
        link.href = url;
        link.setAttribute('download', 'sample.pdf'); // 设置下载文件名
        document.body.appendChild(link);

        // 触发点击下载
        link.click();

        // 下载完成后清理
        document.body.removeChild(link);
        window.URL.revokeObjectURL(url);
      } catch (error) {
        console.error('下载失败:', error);
        this.$message.error('文件下载失败');
      }
    },
    beforeDestroy() {
      // 组件销毁时释放Blob URL
      if (this.pdfUrl) {
        URL.revokeObjectURL(this.pdfUrl);
      }
    }
  }
}
</script>

<style scoped>
.download-btn {
  padding: 10px 20px;
  background-color: #409EFF;
  color: white;
  border: none;
  border-radius: 4px;
  cursor: pointer;
}

.download-btn:hover {
  background-color: #66b1ff;
}
</style>